<html>
  <head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
	
    <script type="text/javascript">
      var CLIENT_ID = '310837256871-o5rrsg5sqbb14tl5l6mk7i7mdh2l9jte.apps.googleusercontent.com';
      var SCOPES = 'https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds';
	  
      /**
       * Called when the client library is loaded to start the auth flow.
       */
      function handleClientLoad() {
        window.setTimeout(checkAuth, 1);
      }

      /**
       * Check if the current user has authorized the application.
       */
      function checkAuth() {
        gapi.auth.authorize(
            {'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': true},
            handleAuthResult);
      }

      /**
       * Called when authorization server replies.
       *
       * @param {Object} authResult Authorization result.
       */
      function handleAuthResult(authResult) {
        var authButton = document.getElementById('authorizeButton');
        var filePicker = document.getElementById('filePicker');
        authButton.style.display = 'none';
        filePicker.style.display = 'none';
        if (authResult && !authResult.error) {
          // Access token has been successfully retrieved, requests can be sent to the API.
          //filePicker.style.display = 'block';
    		gapi.client.load('drive', 'v2', driveAPIOk);

          //filePicker.onchange = uploadFile;
        } else {
          // No access token could be retrieved, show the button to start the authorization flow.
          authButton.style.display = 'block';
          authButton.onclick = function() {
              gapi.auth.authorize(
                  {'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': false},
                  handleAuthResult);
          };
        }
      }

      /**
       * Start the file upload.
       *
       * @param {Object} evt Arguments from the file selector.
       */
      function uploadFile(evt) {
        gapi.client.load('drive', 'v2', function() {
          var file = evt.target.files[0];
          insertFile(file);
        });
      }

      /**
       * Insert new file.
       *
       * @param {File} fileData File object to read data from.
       * @param {Function} callback Function to call when the request is complete.
       */
      function insertFile(fileData, callback) {
        const boundary = '-------314159265358979323846';
        const delimiter = "\r\n--" + boundary + "\r\n";
        const close_delim = "\r\n--" + boundary + "--";

        var reader = new FileReader();
        reader.readAsBinaryString(fileData);
        reader.onload = function(e) {
          var contentType = fileData.type || 'application/octet-stream';
          var metadata = {
            'title': fileData.name,
            'mimeType': contentType
          };

          var base64Data = btoa(reader.result);
          var multipartRequestBody =
              delimiter +
              'Content-Type: application/json\r\n\r\n' +
              JSON.stringify(metadata) +
              delimiter +
              'Content-Type: ' + contentType + '\r\n' +
              'Content-Transfer-Encoding: base64\r\n' +
              '\r\n' +
              base64Data +
              close_delim;

          var request = gapi.client.request({
              'path': '/upload/drive/v2/files',
              'method': 'POST',
              'params': {'uploadType': 'multipart'},
              'headers': {
                'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
              },
              'body': multipartRequestBody});
          if (!callback) {
            callback = function(file) {
              console.log(file)
            };
          }
          request.execute(callback);
        }
      }
	  
	  function driveAPIOk(){
	  retrieveAllFiles(showList);
	  }
	  
	  
	  function showList(result){
		var fileLister = document.getElementById('fileLister');
        fileLister.style.display = 'block';	  
		
		var fileListerHtml = '<option>Select a Spreadsheet</option>';
		for(var i = 0; i < result.length; i++){
			if(result[i].mimeType === 'application/vnd.google-apps.spreadsheet'){
				fileListerHtml += '<option value="' + result[i].id + '" >' + result[i].title + '</option>';
			}
		}
		
		$(fileLister).html(fileListerHtml);
		
		fileLister.onchange = function(evt){
			var targetUrl = 'https://spreadsheets.google.com/feeds/worksheets/' + evt.target.value + '/private/basic?alt=json';
			downloadFile(targetUrl, spreadsheetWorksheets);
		};
	  }
	  
	  function spreadsheetWorksheets(JSON_response){
		var worksheetsObj = eval( '(' + JSON_response + ')' );
		
		if(worksheetsObj.feed){
			if(worksheetsObj.feed.entry){
				if(worksheetsObj.feed.entry.length > 0){
					var worksheetObj = worksheetsObj.feed.entry[0];
					//alert(worksheetObj);
					
					if(worksheetObj.link){
						var listUrl = null;
					
						for(var i = 0; i < worksheetObj.link.length; i++){
							if (worksheetObj.link[i].href.indexOf('/cells/') !== -1){
								listUrl = worksheetObj.link[i].href + '?alt=json';
								break;
							}
						}
						
						if(listUrl){
							downloadFile(listUrl, spreadsheetCells);
						}
					}
				}
			}
		}
	  }
	  
	  function spreadsheetCells(JSON_response){
		var cellsObj = eval( '(' + JSON_response + ')' );
		//alert(cellsObj);
		
		var birthdays = {};
		var table_html = '';
		if(cellsObj.feed.entry){
			var lastRow = null;
			for(var i = 0; i < cellsObj.feed.entry.length; i++){
				var cellTitle = cellsObj.feed.entry[i].title['$t'];
				var cellContent = cellsObj.feed.entry[i].content['$t'];

				var thisRow = cellTitle.substr(1);
				if(!(thisRow in birthdays)){
					birthdays[thisRow] = {};
				}

				
				switch(cellTitle[0]){
					case 'A':
						birthdays[thisRow]['date'] = $.datepicker.parseDate('mm/dd/yy', cellContent);
						break;
					case 'B':
						birthdays[thisRow]['name'] = cellContent;
						break;
					case 'C':
						birthdays[thisRow]['e-mail'] = cellContent;
						break;
				}
				
				if(lastRow){
					if(thisRow !== lastRow){
						lastRow = thisRow;
						table_html += '</tr><tr>';
					}
				}
				else{
					lastRow = thisRow;
					table_html += '<tr>';
				}
				
				table_html += '<td>' + cellContent + '</td>';
				
			}
			
			table_html += '</tr>';
		}
		
		$('#contents_table').html(table_html);
		
	}	  
	  
	  function fileGetComplete(file){
		downloadFile(file, fileDownloadComplete);
	  }
	  
	  function fileDownloadComplete(fileContents){
		alert(fileContents);
	  }
	  
	  
	/**
 * Retrieve a list of File resources.
 *
 * @param {Function} callback Function to call when the request is complete.
 */
function retrieveAllFiles(callback) {
  var retrievePageOfFiles = function(request, result) {
    request.execute(function(resp) {
      result = result.concat(resp.items);
      var nextPageToken = resp.nextPageToken;
      if (nextPageToken) {
        request = gapi.client.drive.files.list({
          'pageToken': nextPageToken
        });
        retrievePageOfFiles(request, result);
      } else {
	  
		if (!callback) {
            callback = function(file) {
              console.log(file)
            };
          }	  
        callback(result);
      }
    });
  }
  var initialRequest = gapi.client.drive.files.list();
  retrievePageOfFiles(initialRequest, []);
}

/**
 * Print a file's metadata.
 *
 * @param {String} fileId ID of the file to print metadata for.
 */
function printFile(fileId) {
  var request = gapi.client.drive.files.get({
    'fileId': fileId
  });
  request.execute(function(resp) {
    console.log('Title: ' + resp.title);
    console.log('Description: ' + resp.description);
    console.log('MIME type: ' + resp.mimeType);
  });
}

function getFile(fileId, callback) {
  var request = gapi.client.drive.files.get({
    'fileId': fileId
  });
  request.execute(function(resp) {
    console.log('Title: ' + resp.title);
    console.log('Description: ' + resp.description);
    console.log('MIME type: ' + resp.mimeType);
	
	callback(resp);
  });
}

/**
 * Download a file's content.
 *
 * @param {File} file Drive File instance.
 * @param {Function} callback Function to call when the request is complete.
 */
function downloadFile(targetUrl, callback) {
  if(targetUrl){
    var accessToken = gapi.auth.getToken().access_token;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', targetUrl);
    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xhr.onload = function() {
      callback(xhr.responseText);
    };
    xhr.onerror = function() {
      callback(null);
    };
    xhr.send();
  } else {
    callback(null);
  }
}
    </script>
    <script type="text/javascript" src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
	<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
	<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>	
  </head>
  <body>
    <!--Add a file picker for the user to start the upload process -->
    <input type="file" id="filePicker" style="display: none" />
    <input type="button" id="authorizeButton" style="display: none" value="Authorize" />
	
	<select id="fileLister" style="display: none;" >
	</select>
	
	<table id="contents_table"></table>
  </body>
</html>